<?php
/**
 * User: 魔十七
 * Date: 2020/10/29
 * Time: 11:00
 */

namespace Samecity\Controller;


use Think\Controller;
class UserController extends Controller
{
    //用户登录注册
    public function user_info(){
        $go_back=['code'=>1,'msg'=>'登陆成功', 'data'=>[]];
        $post = $_POST;
        $code=$post['code'];
        $url="https://api.weixin.qq.com/sns/jscode2session?appid=wx2dc3f62f676163a5&secret=3e92f31115907028c6bf30ed5924ae48&js_code=".$code."&grant_type=authorization_code";
        $data=$this->http($url);
        if($data[0]==200){
            $UserInfo=json_decode($data[1],true);
            //判断用户是否存在
            $map['openid']=$UserInfo['openid'];
            $user=M('user')->field('id,mobile')->where($map)->find();
            //存储用户信息
            $userSaveData=[
                'openid'=>$UserInfo['openid'],
                'session_key'=>$UserInfo['session_key'],
                'sex'=>$post['gender'],
                'nickname'=>$post['nickName'],
                'avatar'=>$post['avatarUrl'],
                ];
            //开启事务
            M()->startTrans();
            try{
                if ($user) {//老用户
                    $res=M('user')->where('id', $user['id'])->save($userSaveData);
                    $userSaveData['mobile'] = $user['mobile'];
                    $userSaveData['id'] = $user['id'];
                } else {//新用户
                    $userSaveData['add_date'] = time();
                    $res = M('user')->add($userSaveData);
                    $userSaveData['id'] = $res;
                }
                //提交事务
                M()->commit();
                unset($userSaveData['openid']);
                unset($userSaveData['session_key']);
                $go_back['data']=$userSaveData;
                $go_back['code']=0;
            }catch (\Exception $ex) {
                //回滚事务
                M()->rollback();
                $go_back['msg']=$ex->getMessage();
            }
            $this->ajaxReturn($go_back);
        }else{
            $this->ajaxReturn($go_back);
        }

    }

    //获取用户手机号
    public function user_tel(){
        $go_back=['code'=>1,'msg'=>'获取成功', 'data'=>[]];
        $post = $_POST;
        $map['id']=$_POST['uid'];
        $user=M('user')->field('*')->where($map)->find();
        if($user){
            $encryptedData=$post['encryptedData'];
            $iv=$post['iv'];
            $sessionKey=$user['session_key'];
            $errCode = $this->decryptData($sessionKey,"wx2dc3f62f676163a5",$encryptedData,$iv,$data);
            if ($errCode == 0) {
                $phoneNumber=json_decode($data,true);
                $mobile=$phoneNumber['phoneNumber'];
                    M('user')->where($map)->save(['mobile'=>$mobile]);
                    $user['mobile']=$mobile;
                    $go_back['code']=0;
                    $go_back['data']=$user;
            } else {
                $go_back['msg']=$errCode;
            }
        }
        $this->ajaxReturn($go_back);
    }

    //解密手机号
    private function decryptData($sessionKey,$appid,$encryptedData,$iv,&$data)
    {
        if (strlen($sessionKey) != 24) {return -41001;}
        $aesKey=base64_decode($sessionKey);
        if (strlen($iv) != 24) {return -41002;}
        $aesIV=base64_decode($iv);
        $aesCipher=base64_decode($encryptedData);
        $result=openssl_decrypt($aesCipher,"AES-128-CBC",$aesKey,1,$aesIV);
        $dataObj=json_decode($result);
        if( $dataObj  == NULL ){return -410031;}
        if( $dataObj->watermark->appid != $appid){return -41003;}
        $data = $result;
        return 0;
    }

    /**
     * curl  请求
     * @param $url
     * @param $method
     * @param null $postfields
     * @param array $headers
     * @param bool $debug
     * @return array
     */
    private function http($url, $method = '', $postfields = null, $headers = array(), $debug = false)
    {
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                    $this->postdata = $postfields;
                }
                break;
        }
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        $response = curl_exec($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo '=====info=====' . "\r\n";
            print_r(curl_getinfo($ci));
            echo '=====$response=====' . "\r\n";
            print_r($response);
        }
        curl_close($ci);
        return array($http_code, $response);
    }
}